package cn.qicaiwang.open.app.controller;

import cn.hutool.core.util.StrUtil;
import cn.qicaiwang.open.common.enums.ResultStatusCodeEnum;
import cn.qicaiwang.open.common.response.ResponseResult;
import cn.qicaiwang.open.common.utils.StringUtils;
import cn.qicaiwang.open.common.utils.jwt.JwtTokenUtil;
import cn.qicaiwang.open.system.model.dto.SystemUserDTO;
import cn.qicaiwang.open.system.model.entity.SystemUser;
import cn.qicaiwang.open.system.service.ISystemUserService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/qcwapp/appuser")
public class AppUserController {
    @Autowired
    private ISystemUserService systemUserService;


    /**
     * app在添加用户的时候，同步在系统的用户表同步下注册 用于用户的和客服进行对话
     *
     * @param systemUserDTO
     * @return
     */
    @PostMapping("add")
    public ResponseResult add(@RequestBody SystemUserDTO systemUserDTO) {

        if (StrUtil.isBlank(systemUserDTO.getPhone())) {//手机号
            return ResponseResult.error(ResultStatusCodeEnum.MOBILE_NOT_EMPTY);
        }

        SystemUser temp = systemUserService.selectOneByMobile(systemUserDTO.getPhone());
        if (temp != null) {
            return ResponseResult.error(ResultStatusCodeEnum.USER_EXIST);
        }

        boolean b = systemUserService.saveAppBean(systemUserDTO);
        if (b) {
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    @PostMapping("getToken")
    public ResponseResult getToken(@RequestBody SystemUserDTO systemUserDTO) {
        // 1. 验证用户是否存在
        SystemUser temp = systemUserService.selectOneByMobile(systemUserDTO.getUsername());
        if (temp == null) {
            return ResponseResult.error(ResultStatusCodeEnum.USER_NOT_EXIST);
        }

        // 2. 同步头像
        String avatar = systemUserService.selectWithAvatar(systemUserDTO.getUsername());
        if (StringUtils.isNotBlank(avatar)) {
            String fullAvatarUrl = "http://qcwimg.it110.top/" + avatar;
            systemUserService.updateAvatarByUsername(systemUserDTO.getUsername(), fullAvatarUrl);
        }

        // 3. 生成Token
        String token = JwtTokenUtil.generateTokenByUsernameAndPassword(
                temp.getUsername(),
                temp.getPassword(),
                temp.getId()
        );
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",token);
        jsonObject.put("userId",temp.getId());

        return ResponseResult.ok(jsonObject);
    }
}
